<template>
  <div class="edit-container">
    <el-form v-loading="formLoading" ref="form" :model="form" :rules="rules" label-width="12 0px">
      <el-form-item label="logo" prop="businessFace">
        <div style="display: flex;align-items: center;">
          <el-image v-if="form.businessFace" :src="imageUrl + form.businessFace" class="img"
                    referrerpolicy="no-referrer"></el-image>
          <el-button type="primary" @click="uploads.show=true" size="mini">选择图片</el-button>
        </div>
      </el-form-item>
      <el-form-item label="商家轮播图" prop="file">
        <div class="imgList">
          <template v-for="item in form.file">
            <el-image v-if="item.fileType === 1" :key="item.id" :src="imageUrl + item.url" class="img"
                      referrerpolicy="no-referrer"></el-image>
            <video v-else-if="item.fileType === 2" :key="item.id" :src="imageUrl +item.url" controls width="120"
                   height="120"></video>
          </template>
        </div>
        <el-button type="primary" @click="imgUploads.show=true" size="mini">选择图片</el-button>
      </el-form-item>
      <el-form-item label="商家名称" prop="businessName">
        <el-input v-model="form.businessName" placeholder="商家名称" maxlength="30" class="col"></el-input>
      </el-form-item>
      <el-form-item label="商家电话" prop="businessPhone">
        <el-input v-model="form.businessPhone" placeholder="商家电话" maxlength="11" class="col"></el-input>
      </el-form-item>
      <el-form-item label="用户手机" prop="userPhone">
        <el-input v-model="form.userPhone" placeholder="需关联用户登录手机号" maxlength="11" class="col"></el-input>
      </el-form-item>
      <el-form-item label="商家标签" prop="label">
        <el-input v-model="form.label" placeholder="商家标签" maxlength="30" class="col"></el-input>
      </el-form-item>
      <el-form-item label="限时优惠" prop="limitedTimeOffer">
        <el-input v-model="form.limitedTimeOffer" placeholder="限时优惠" maxlength="30" class="col"></el-input>
      </el-form-item>
      <el-form-item label="商家类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择" class="col">
          <el-option
              v-for="item in businessTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商家地区" prop="areaId">
        <el-cascader class="col"
                     placeholder="可输入地区名称进行搜索"
                     v-model="value"
                     :options="options"
                     clearable
                     :props="{ expandTrigger: 'hover' }"
                     filterable
                     @change="handleChange"></el-cascader>
      </el-form-item>
      <!--      <el-form-item label="商家地址" prop="address">{{ form.address }}-->
      <!--        <el-button icon="el-icon-location" size="mini" type="primary" @click="showChoosePosition=true">-->
      <!--          点击选择位置-->
      <!--        </el-button>-->
      <!--      </el-form-item>-->
      <el-form-item label="商家地址" prop="address">
        <el-input v-model="form.address" maxlength="50" class="col" placeholder="请输入商家地址"></el-input>
      </el-form-item>
      <el-form-item label="商家挂售额度" prop="variablePresent">
        <el-input v-model="form.variablePresent" placeholder="商家挂售额度"
                  oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                  @blur="form.variablePresent=$event.target.value"
                  maxlength="8" class="col"></el-input>
      </el-form-item>
      <el-row style="display: flex;">
        <el-col :span="8">
          <el-form-item label="导航定位" prop="longitude">
            <el-input v-model="form.latitudeAndLongitude" placeholder="请输入商家所在经纬度"></el-input>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="8">-->
        <!--          <el-form-item label="纬度" prop="latitude">-->
        <!--            <el-input v-model="form.latitude" maxlength="12"  placeholder="请输入商家所在纬度"></el-input>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="8">
          <el-button icon="el-icon-location" size="mini" type="primary" style="margin-left: 30px;height: 37px"
                     @click="changePosition">点击选择经纬度
          </el-button>
        </el-col>
      </el-row>
      <!--      <el-form-item label="评分" prop="score">-->
      <!--          <el-rate v-model="form.score" ></el-rate>-->
      <!--      </el-form-item>-->
      <el-form-item label="营业时间" prop="businessHoursBegin">
        <el-time-select
            placeholder="起始时间"
            :picker-options="{
      start: '00:00',
      end: '24:00',
    }"
            v-model="form.businessHoursBegin" style="margin-right: 8px;width: 176px;">
        </el-time-select>
        <el-time-select
            placeholder="结束时间"
            :picker-options="{
      start: '00:00',
      end: '24:00',
    }"
            v-model="form.businessHoursEnd" style="width: 176px;">
        </el-time-select>
      </el-form-item>
      <el-form-item label="营业状态" prop="businessStatus">
        <el-select v-model="form.businessStatus" placeholder="请选择">
          <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否为甄选" prop="isPick">
        <el-select v-model="form.isPick" placeholder="请选择">
          <el-option
              v-for="item in actList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="内容" prop="goodsDetails">
        <div style="width: 100%;">
          <Tinymce v-model="form.businessDetails"
                   style="width: 100%; min-height: 300px; box-sizing: border-box;"></Tinymce>
        </div>
      </el-form-item>


      <el-form-item>
        <el-button v-loading="saveLoading" element-loading-background="rgba(0, 0, 0, 0.3)" type="primary"
                   @click="handlerSubmit" v-has-permi="['admin:business:save']">保存
        </el-button>
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>
    <el-dialog v-if="showChoosePosition" :close-on-click-modal="false" :close-on-press-escape="false"
               :destroy-on-close="true"
               :visible.sync="showChoosePosition" append-to-body title="选择位置" top="5vh"
               width="40%">
      <iframe v-if="showChoosePosition" id="choosePosition" frameborder=0
              src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=ZILBZ-FEDCL-6M3PO-M7GUW-PXP5T-ABFB4&referer=零工超市"
              style="width: 100%;height: 500px">
      </iframe>
      <span slot="footer" class="dialog-footer">
            <el-button class="primary" type="primary" @click="showChoosePosition = false">确 定</el-button>
          </span>
    </el-dialog>
    <el-dialog
        :visible.sync="uploads.show"
        title="上传封面"
        :append-to-body="true"
        destroy-on-close
        :close-on-click-modal="false"
        width="1000px">
      <UploadFile
          v-if="uploads.show"
          :multiple="uploads.multiple"
          @getFile="getFile"
          :module-id="1"
          :business-id="form.id"
          ref="uploads"
      />
    </el-dialog>
    <el-dialog
        :visible.sync="imgUploads.show"
        title="上传图片"
        :append-to-body="true"
        destroy-on-close
        :close-on-click-modal="false"
        width="1000px">
      <UploadFile
          v-if="imgUploads.show"
          :multiple="imgUploads.multiple"
          :module-id="1"
          :business-id="form.id"
          @getFile="getImage"
          ref="uploads"
      />
    </el-dialog>
  </div>
</template>
<script>
import {detail, optionsList, save} from "@/api/business";
import {getForm} from "@/utils/utils";
import UploadFile from "@/components/File/UploadFile.vue";
import Tinymce from "@/components/Tinymce/index.vue";

export default {
  components: {Tinymce, UploadFile},
  props: {
    id: {
      default: null
    },
    businessTypeList: [],
  },
  data() {
    return {
      form: {
        id: null,
        businessName: '',
        businessPhone: '',
        userPhone: '',
        businessFace: '',
        label: '',
        type: '',
        address: '',
        latitude: '',
        longitude: '',
        businessHoursBegin: '',
        businessHoursEnd: '',
        businessTime: '',
        businessStatus: '',
        limitedTimeOffer: '',
        file: [],
        fileId: '',
        areaId: '',
        cityId: '',
        value: '',
        businessDetails: '',
        isPick: '',
        latitudeAndLongitude: '',
        variablePresent: ''
      },
      value: [],
      options: [{
        value: '',
        label: '',
        children: [{
          value: '',
          label: '',
          children: [{
            value: '',
            label: ''
          }]
        }]
      }],

      showChoosePosition: false,
      rules: {
        businessName: [{required: true, message: '请填写商家名称', trigger: ['blur']}],
        businessPhone: [{required: true, message: '请填写商家电话', trigger: ['blur']}],
        userPhone: [{required: true, message: '请填写商家电话', trigger: ['blur']}],
        businessFace: [{required: true, message: '请设置商家头像', trigger: ['blur']}],
        label: [{required: true, message: '请填写标签', trigger: ['blur']}],
        type: [{required: true, message: '请选择类型', trigger: ['blur']}],
        address: [{required: true, message: '请填写地址', trigger: ['blur']}],
        businessHoursBegin: [{required: true, message: '请选择开始时间', trigger: ['blur']}],
        businessHoursEnd: [{required: true, message: '请选择结束时间', trigger: ['blur']}],
        businessStatus: [{required: true, message: '请选择营业状态', trigger: ['blur']}],
        score: [{required: true, message: '请评分', trigger: ['blur']}],
        file: [{required: true, message: '请选择商家轮播图', trigger: ['blur']}],
        areaId: [{required: true, message: '请选择商家地区', trigger: ['blur']}],
        longitude: [{required: true, message: '请选择商家所在经度', trigger: ['blur']}],
        latitude: [{required: true, message: '请选择商家所在纬度', trigger: ['blur']}],
        variablePresent: [{required: true, message: '请填写商家挂售额度', trigger: ['blur']}],
      },
      roles: [],
      saveLoading: false,
      formLoading: false,
      uploads: {
        show: false,
        multiple: false,
      },
      typeList: [{id: 1, name: "营业中"}, {id: 2, name: "未营业"},],
      actList: [{id: 1, name: "是"}, {id: 0, name: "否"}],
      imageUrl: '',
      imgUploads: {
        show: false,
        multiple: true,
      },
    }
  },
  mounted() {
    this.imageUrl = process.env.VUE_APP_IMAGE_URL
    this.getOptions();
    if (this.id) {
      this.getDetail();
    }
    window.addEventListener('message', (event) => {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      let loc = event.data;
      if (loc && loc.module == 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        this.form.latitude = loc.latlng.lat;
        this.form.longitude = loc.latlng.lng;
        this.form.address = loc.poiaddress
      }
    }, false);
  },
  methods: {
    changePosition() {
      window.open('https://lbs.qq.com/getPoint/', '_blank');
      //window.location.href = 'https://api.map.baidu.com/lbsapi/getpoint/index.html'
    },
    handleChange(value) {
      this.form.value = value
      this.form.areaId = value[2]
      this.form.cityId = value[1]
    },
    getOptions() {
      optionsList().then(res => {
        this.options = res
      })
    },
    getDetail() {
      this.formLoading = true
      detail(this.id).then(res => {
        getForm(res, this.form);
        let arr = this.form.businessTime.split("-")
        this.form.businessHoursBegin = arr[0]
        this.form.businessHoursEnd = arr[1]
        this.value = res.value
        this.form.latitudeAndLongitude = res.latitude + ',' + res.longitude
      }).finally(() => {
        this.formLoading = false;
      })
    },
    getFile(fileList) {
      this.form.businessFace = fileList[0].url
      this.uploads.show = false
    },
    getImage(fileList) {
      this.form.file = fileList
      this.imgUploads.show = false
      let ids = []
      this.form.file.forEach(item => {
        ids.push(item.id)
      })
      this.form.fileId = ids.join(',')
    },
    handlerSubmit() {
      if (this.saveLoading || this.formLoading) {
        return;
      }
      const latitudeAndLongitude = this.form.latitudeAndLongitude;
      const parts = latitudeAndLongitude.split(',');
      this.form.latitude = parts[0];
      this.form.longitude = parts[1];
      this.$refs.form.validate(valid => {
        if (!valid) return;
        this.saveLoading = true;
        this.form.businessTime = this.form.businessHoursBegin + "-" + this.form.businessHoursEnd
        save(this.form).then(() => {
          this.$message.success('保存成功');
          this.close();
        }).finally(() => {
          this.saveLoading = false
        })
      })
    },
    close() {
      this.$emit('hideEditDialog')
    }
  }
}
</script>
<style lang="scss" scoped>

.col {
  width: 450px;
}

.img {
  width: 120px;
  height: 120px;
  margin-right: 10px;
}

/* 添加的全局样式 */
.tox-tinymce {
  width: 100% !important;
}

.tox-toolbar-overlord, .tox-toolbar__primary {
  display: flex;
  flex-wrap: wrap;
}
</style>
